
import { goodscount, goodslist } from "@/request/api"
const state = {
    goodsList: [],
    size: 3,//一页几条
    page: 1,//页码
    count: 0//总条数
}

const getters = {
    getGoods(state) {
        return state.goodsList
    },
    getSize(state) {
        return state.size
    },
    getCount(state) {
        return state.count
    }

}

const mutations = {
    CHANGEGOODS(state, payload) {
        state.goodsList = payload
    },
    CHANGECOUNT(state, payload) {
        state.count = payload
    }
}

const actions = {
    GetGoodsInfo(context) {
        goodslist({
            page: context.state.page,
            size: context.state.size
        })
            .then(res => {
                /*
                当当前页面不是第一页时并且在删除当前页面的最后一项时会出现一个bug
                它请求的接口还是当前页的数据,应该page -1
    
                */
                if (res.code == 200) {
                    let list = res.list ? res.list : []
                    if (context.state.page != 1 && list.length == 0) {
                        context.dispatch('GetPageInfo',context.state.page -1)
                    } else {
                        context.commit('CHANGEGOODS', res.list)
                    }
                }
            })
    },
    GetCountInfo(context) {
        goodscount()
            .then(res => {
                if (res.code == 200) {
                    context.commit('CHANGECOUNT', res.list[0].total)
                }
            })
    },
    // 切换页码重新请求
    GetPageInfo(context, payload) {
        // 给页码重新赋值
        context.state.page = payload
        // 重新调用接口
        context.dispatch('GetGoodsInfo')

    }
}

export default {
    state,
    getters,
    mutations,
    actions,
    namespaced: true
}